package com.liang.auth.domain.service.impl;

import cn.hutool.json.JSONUtil;
import com.liang.auth.domain.bo.AuthPermissionBO;
import com.liang.auth.domain.convert.AuthPermissionBOConverter;
import com.liang.auth.domain.service.AuthPermissionDomainService;
import com.liang.auth.infra.basic.entity.AuthPermission;
import com.liang.auth.infra.basic.service.AuthPermissionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class AuthPermissionDomainServiceImpl implements AuthPermissionDomainService {

    private final AuthPermissionService authPermissionService;
    private final RedisTemplate<String, Object> redisTemplate;
    private String authPermissionPrefix = "auth:permission";


    @Override
    public void save(AuthPermissionBO authPermissionBO) {
        AuthPermission authPermission = AuthPermissionBOConverter.INSTANCE.convertBO2PO(authPermissionBO);
        log.info("AuthPermissionDomainServiceImpl.save.authPermission：{}", authPermission);
        authPermissionService.save(authPermission);
    }

    @Override
    public void update(AuthPermissionBO authPermissionBO) {
        AuthPermission authPermission = AuthPermissionBOConverter.INSTANCE.convertBO2PO(authPermissionBO);
        log.info("AuthPermissionDomainServiceImpl.update.authPermission：{}", authPermission);
        authPermissionService.updateById(authPermission);
    }

    @Override
    public void delete(Long id) {
        authPermissionService.removeById(id);
    }

    @Override
    public List<String> getPermission(String userName) {
        String key = authPermissionPrefix + ":" + userName;
        String value = (String) redisTemplate.opsForValue().get(key);
        List<AuthPermission> permissionList = JSONUtil.toList(value, AuthPermission.class);
        return permissionList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());
    }
}
